// Copyright 2020 morgine.com. All rights reserved.

package services

import (
	"flag"
	"gitee.com/tugoer/psys/env"
	"gitee.com/tugoer/psys/storage"
	orm "github.com/jinzhu/gorm"
	"github.com/morgine/cfg"
	"github.com/morgine/database/gorm"
	"github.com/morgine/database/postgres"
	"github.com/morgine/service"
	"net/http"
	"os"
)

var Gorm *orm.DB
var ImgStore storage.Interface
var ImgService storage.HttpHandler

func init() {
	configFile := flag.String("c", "config.toml", "配置文件")
	flag.Parse()
	var container = service.NewContainer()
	var cfgService = cfg.NewService(cfg.NewFileStorageService(*configFile))
	envs, err := cfgService.Get(container)
	if err != nil {
		panic(err)
	}
	err = envs.UnmarshalSub("server", env.Env)
	if err != nil {
		panic(err)
	}
	err = os.MkdirAll(env.Env.LocalImgDir, os.ModePerm)
	if err != nil {
		panic(err)
	}
	var store *storage.LocalStorage
	store, err = storage.NewLocalStorage(env.Env.LocalImgDir, env.Env.LocalImgServeHost, func(header http.Header) {
		//cros.AddDefaultCrossSiteAccess(header)
	})
	ImgStore = store
	ImgService = store
	var pgService = postgres.NewService("postgres", cfgService)
	var gormService = gorm.NewService("gorm", cfgService, pgService)
	Gorm, err = gormService.Get(container)
	if err != nil {
		panic(err)
	}
}
